﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace ThinNet.WebApi
{
    public abstract class Controller : ControllerBase, IActionFilter, IFilterMetadata, IAsyncActionFilter, IDisposable
    {
        protected Controller()
        {

        }


        #region JsonResult

        [NonAction]
        public virtual JsonResult Json(object data)
        {
            return new JsonResult(data);
        }
        

        [NonAction]
        public virtual JsonResult Json(object data, JsonSerializerSettings serializerSettings)
        {
            if (serializerSettings == null)
            {
                throw new ArgumentNullException("serializerSettings");
            }
            return new JsonResult(data, serializerSettings);
        }

        #endregion

        #region IDisposable Member              

        public void Dispose()
        {
            this.Dispose(true);
        }

        protected virtual void Dispose(bool disposing)
        {

        }

        #endregion

        #region IActionFilter Member


        [NonAction]
        public virtual void OnActionExecuted(ActionExecutedContext context)
        {
            
        }
        [NonAction]
        public virtual void OnActionExecuting(ActionExecutingContext context)
        {

        }
        
        [NonAction]
        public virtual async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            this.OnActionExecuting(context);
            if (context.Result == null)
            {
                ActionExecutedContext context2 = await next.Invoke();
                this.OnActionExecuted(context2);
            }
        }

        #endregion
    }
}
